import { DynamicIndex } from "./types/commonTypes";

export default class {
  static stringify(data: DynamicIndex) {
    let res: string = "";
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        const value = data[key];
        if (typeof value === "object") {
          res += `${key}=${JSON.stringify(value)}&`
          continue;
        }
        res += `${key}=${value}&`;
      }
    }
    return res.substring(0, res.length - 1);
  }
  static parse(data: string) {
    const res:DynamicIndex = {};
    const dataArr = data.split("&");
    const KVReg: RegExp = /(\w+)=([\s\S]+)/;
    for (let i = 0, len = dataArr.length; i < len; i++) {
      const item: string = dataArr[i];
      const matchRes:string[] = item.match(KVReg) || [];
      const key = matchRes[1];
      const value = matchRes[2];
      res[key] = value;
    }
    return res;
  }
}